package com.example.szl7033.camera_1_preview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private Camera mCamera;
    private CameraPreview mPreview;

    private String TAG = "shi_MainActivity";

    //Android6.0 以上需要运行时权限授权
    private void checkPermission(){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return;
        }
        String[] permission = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        List<String> mPermissionList = new ArrayList<>();
        mPermissionList.clear();
        for (int i = 0; i < permission.length; i++) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, permission[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permission[i]);
            }
        }
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            Toast.makeText(MainActivity.this,"已经授权",Toast.LENGTH_LONG).show();
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 2);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        //调用权限检测
        checkPermission();

        mCamera = getCameraInstance();//获取一个camera实例
        mPreview = new CameraPreview(this, mCamera);//获取一个preview实例

        FrameLayout preview =  findViewById(R.id.camera_preview);//获取一个帧布局实例
        preview.addView(mPreview);//将帧布局与surface view进行关联

        //设置相机参数
        printCameraParameters();

        ///*
        //拍照
        Button buttonCapture = (Button)findViewById(R.id.button_capture);
        buttonCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCamera.takePicture(null, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] bytes, Camera camera) {
                        @SuppressLint("SdCardPath") String path = "/sdcard/temp_" + mPreview.pictureSize.width + "x" + mPreview.pictureSize.height + ".png";
                        File tempFile = new File(path);
                        try {
                            FileOutputStream fos = new FileOutputStream(tempFile);
                            fos.write(bytes);
                            fos.close();
                            Log.d(TAG,"save succeeded");
                        } catch (FileNotFoundException e) {
                            Log.d(TAG, "File not found: " + e.getMessage());
                        } catch (IOException e) {
                            Log.d(TAG, "Error accessing file: " + e.getMessage());
                        }

                        //拍照成功提示
                        Toast.makeText(MainActivity.this,"照片已保存",Toast.LENGTH_SHORT).show();

                        //重新开始预览
                        mPreview.surfaceCreated(mPreview.getHolder());
                    }
                });
            }
        });
        //*/

        //注册预览回调函数
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //方法：打印相机参数信息
    private void printCameraParameters(){
        //获取可用摄像头的数量
        Log.d(TAG, String.valueOf(Camera.getNumberOfCameras()));

        //获取摄像头信息
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        Log.d(TAG, String.valueOf(cameraInfo.facing+cameraInfo.orientation));

        //获取相机参数
        Camera.Parameters parameters = mCamera.getParameters();
        List<Camera.Size> supportedSizes = parameters.getSupportedPreviewSizes();
        for(Camera.Size previewSize : supportedSizes){  //打印预览支持尺寸
            Log.d(TAG,"preview size:" + String.valueOf(previewSize.width) + "*" + String.valueOf(previewSize.height) + " 比例为：" + String.valueOf((float)previewSize.width / previewSize.height));
        }
        supportedSizes.clear();
        supportedSizes = parameters.getSupportedPictureSizes();
        for(Camera.Size pictureSize : supportedSizes){  //打印照片支持尺寸
            Log.d(TAG,"picture size:" + String.valueOf(pictureSize.width) + "*" + String.valueOf(pictureSize.height) + " 比例为：" + String.valueOf((float)pictureSize.width / pictureSize.height));
        }
        //打印预览支持格式
        List<Integer> supportedPreviewFormat = parameters.getSupportedPreviewFormats();
        for(Integer previewFormat : supportedPreviewFormat){
            switch (previewFormat){
                case 17 : Log.d(TAG,"Format:NV21");break;
                case 842094169 : Log.d(TAG,"Format:YV12");break;
                default:
            }
        }
        //打印预览帧率
        List<Integer> previewRate = parameters.getSupportedPreviewFrameRates();
        for(Integer rate : previewRate){
            Log.d(TAG,"preview frame rates : " + String.valueOf(rate));
        }
    }

    //方法：获取相机实例
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }



    //方法：获取合理的预览角度
    private int getCameraDisplayOrientation(Camera.CameraInfo cameraInfo) {
        int rotation = getWindowManager().getDefaultDisplay().getRotation();    //获取屏幕方向
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }
        int result;
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {       //获取摄像头传感器方向
            result = (cameraInfo.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (cameraInfo.orientation - degrees + 360) % 360;
        }
        return result;
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mCamera.release();

        mCamera = null;
        mPreview = null;
    }
}
